package com.hc.baselibray;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import java.util.ArrayList;

//5。0以上才有
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class JobWakeUpService extends JobService {
    private final int JobWakeUp = 10;

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        //开启定时器，定时轮询，看看messageservice有没有被杀死
        //如果啥事启动，轮询onstartJob
        boolean messageServiceAlive = serviceAlive(GuardService.class.getName());
        if (!messageServiceAlive) {
            startService(new Intent(this, GuardService.class));
        }
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //开启一个轮询
        JobInfo.Builder builder = new JobInfo.Builder(JobWakeUp, new ComponentName(getPackageName(), com.hc.baselibray.JobWakeUpService.class.getName()));
        builder.setPeriodic(2000);
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(builder.build());
        return START_STICKY;
    }

    /**
     * 判断服务是否开启
     *
     * @return
     */
    private boolean serviceAlive(String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }
}